import { BasicDrawer, useDrawerInner } from "@/components/Drawer";
import { BasicForm, FormSchema, useForm } from "@/components/Form";
import { message } from "antd";
import { useTranslation } from "react-i18next";
import "./index.less";
import { bookkeepApi } from "@/api/statisticalReport/financialTransactions";
import { convertToTimestamp } from "@/utils/util";
let reload: Function;
let entryId: string;
const index = (props: { register: Fn }) => {
	const { t } = useTranslation();
	const en_vi = "statisticalReport.financialTransactions";
	const formSchema: FormSchema[] = [
		{
			label: t(`${en_vi}.transactionDate`),
			field: "txnDate",
			component: "DatePicker"
		},
		{
			label: t(`${en_vi}.accountingSubject`),
			field: "accountId",
			component: "Input"
		},
		{
			label: t(`${en_vi}.debitAccount`),
			field: "debitAccount",
			component: "Input"
		},
		{
			label: t(`${en_vi}.creditAccount`),
			field: "creditAccount",
			component: "Input"
		},
		{
			label: t(`${en_vi}.debitAmount`),
			field: "debitAmount",
			component: "InputNumber"
		},
		{
			label: t(`${en_vi}.creditAmount`),
			field: "creditAmount",
			component: "InputNumber"
		},
		{
			label: t(`${en_vi}.remark`),
			field: "remark",
			component: "InputTextArea"
		}
	];

	const [registerDrawer, { closeDrawer }] = useDrawerInner(props.register, async data => {
		reload = data.reload;
		await resetFields();
		if (data.record) {
			entryId = data.record.entryId;
			setFieldsValue(data.record);
		}
	});

	const [register, { validateFields, setFieldsValue, resetFields }] = useForm({
		schemas: formSchema,
		labelWidth: 100,
		baseColProps: {
			span: 24
		},
		initialValues: {
			status: "0"
		}
	});
	const handleSubmit = async () => {
		const formValue = await validateFields();
		formValue.txnDate = convertToTimestamp(formValue.txnDate, true);
		let api = bookkeepApi.bookkeepCreate;
		if (entryId) {
			api = bookkeepApi.bookkeepUpdate;
		}
		const res = await api({ ...formValue, entryId });
		if (res) {
			entryId ? message.success(t("kevin_ui.updateSuccess")) : message.success(t("kevin_ui.addedSuccessfully"));
			reload();
			closeDrawer();
			entryId = "";
		}
	};
	return (
		<BasicDrawer showFooter={true} {...props} register={registerDrawer} ok={handleSubmit}>
			<div className="warehouses">
				<BasicForm register={register}></BasicForm>
			</div>
		</BasicDrawer>
	);
};
export default index;
